package server;

import comunications.ClientComunicateInterface;
import gameState.Player;
import gameState.Ring;
import gameState.Table;

import java.net.InetAddress;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.logging.Level;
import java.util.logging.Logger;



public class Server {
	
	private static final Server SERVER_INSTANCE = new Server();
	private String localIP;
	private Ring ring;
    private Table table;

    Logger logger = Logger.getLogger(this.getClass().getSimpleName());



	public void addToRing(Player c) {
		ring.addPlayerToRing(c);
	}


	private Server(){
		this.ring = Ring.getInstance();
                this.table = Table.getInstance();
		try{  this.localIP=InetAddress.getLocalHost().getHostAddress();  }
		catch(java.net.UnknownHostException e) {  e.printStackTrace();  }
	}


	public static synchronized Server getInstance(){
		return SERVER_INSTANCE;
	}


	public void registryStartup(){
		try{
		
                    int portaServerRMI = 60000;

                    Registry registry = LocateRegistry.createRegistry(portaServerRMI);

                    ServerComunicateImpl c = new ServerComunicateImpl();

		    registry.rebind("ServerComunicateImpl", c);
		    
		    logger.log(Level.INFO, "Server Running...\n\n");
		    
		}catch (Exception e) {
			logger.log(Level.WARNING, "[Server] Exception in registryStartup");
			e.printStackTrace();
		}
	}


        public void startGame(){

        try{
            table.resetTableForNewGame(ring);
            Player player = ring.getPlayer(0);
            table.setCurrentPlayer(player);
            System.out.println(table.getCurrentPlayer().getName());
           

            for (int i=0; i<ring.size(); i++){
                player = ring.getPlayer(i);

                Registry registry = LocateRegistry.getRegistry(player.getIp(), player.getPort());
                ClientComunicateInterface cci = (ClientComunicateInterface)registry.lookup("ClientComunicateImpl");
                cci.bringRing(ring);
                cci.bringFirstTable(table);
                cci.creaPlayerActions();
                logger.log(Level.FINE, "[Server] ring e firstTable inviati a "+player.getIp());
            }
            player = ring.getPlayer(0);
            Registry registry = LocateRegistry.getRegistry(player.getIp(), player.getPort());
            ClientComunicateInterface cci = (ClientComunicateInterface)registry.lookup("ClientComunicateImpl");
            cci.bringTable(table);
            logger.log(Level.FINE, "[Server] table inviato a "+player.getIp());
        }
        catch(Exception e){
            e.printStackTrace();
        }

            ring.deleteRing();
            logger.log(Level.INFO, "Game started\n\n\n");
            try {Thread.sleep(2000);}
            catch(InterruptedException ex){ex.printStackTrace();}
            logger.log(Level.INFO, "Server ready for new requests");

        }


        public void showOnScreen(){

            //dimensioni colonne al netto di "[  ]"
            int dimID = 6;
            int dimIP = 15;
            int dimPORT = 6;
            int dimNAME = 20;

            System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
            System.out.print("[ NÀö][   ID   ][        IP       ][  PORT  ][         NAME         ]\n");
            System.out.print("====================================================================\n");
            for (int i=0; i<ring.size(); i++){
                Player p = ring.getPlayer(i);
                // [NÀö]column
                System.out.print("[");
                System.out.print(this.getSpaces(1-(i/10)));
                System.out.print(i);
                System.out.print(" ]");

                // [ID]column
                System.out.print("[ ");
                System.out.print(this.getSpaces(((dimID-Integer.toString(p.getId()).length())/2)+((dimID-Integer.toString(p.getId()).length())%2)));
                System.out.print(p.getId());
                System.out.print(this.getSpaces(((dimID-Integer.toString(p.getId()).length())/2)));
                System.out.print(" ]");

                // [IP]column
                System.out.print("[ ");
                System.out.print(this.getSpaces(((dimIP-p.getIp().length())/2)+((dimIP-p.getIp().length())%2)));
                System.out.print(p.getIp());
                System.out.print(this.getSpaces(((dimIP-p.getIp().length())/2)));
                System.out.print(" ]");

                // [PORT]column
                System.out.print("[ ");
                System.out.print(this.getSpaces(((dimPORT-Integer.toString(p.getPort()).length())/2)+((dimPORT-Integer.toString(p.getPort()).length())%2)));
                System.out.print(p.getPort());
                System.out.print(this.getSpaces(((dimPORT-Integer.toString(p.getPort()).length())/2)));
                System.out.print(" ]");

                // [NAME]column
                System.out.print("[ ");
                System.out.print(this.getSpaces(((dimNAME-p.getName().length())/2)+((dimNAME-p.getName().length())%2)));
                System.out.print(p.getName());
                System.out.print(this.getSpaces(((dimNAME-p.getName().length())/2)));
                System.out.print(" ]\n");
            }
            System.out.print("\n\n");
        }


        public String getSpaces(int lenght){
            String s="";
            for (int i=0; i<lenght; i++){
                s+=" ";
            }
            return s;
        }


        public void keyboardListener(){
            try{
                System.out.println("Press ENTER to start the game");
                int key = System.in.read();
                if(key==10){
                    this.startGame();
                }
            }
            catch(Exception e){e.printStackTrace();}

        }

}
	